<script setup lang="ts">
import {onMounted, reactive, ref} from 'vue';
import getLocation from '@/utils/geoLocation.js';// 引入地理位置获取工具函数
import {useUserStore} from '@/stores/userStore.js'
import {ElMessage, FormInstance} from "element-plus";
import {adminUserStore} from "@/stores/adminStore";

const errorMessage = ref('');
const formRef = ref<FormInstance>()
const LAST_LOGIN_IP = ref(''); // 存储上次登录的IP地址
const form = reactive({
  account: '',
  password: '',
});
const rules = {
  account: [
    {required: true, message: '请输入账号', trigger: 'blur'}
  ],
  password: [
    {required: true, message: '请输入密码', trigger: 'blur'}
  ],
  phone: [
    {required: true, message: '请输入手机号', trigger: 'blur'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur'},
  ],
  code: [
    {required: true, message: '请输入验证码', trigger: 'blur'}
  ],
};
const userStore = useUserStore()
const adminStore = adminUserStore();
const loginType = ref<'password' | 'phone'>('password'); // 登录方式
// 切换登录方式
const switchLoginType = (type: 'password' | 'phone') => {
  loginType.value = type;
  resetForm();
};
const showMessage = (type: any, message: any) => {// 显示消息提示
  ElMessage({
    type,
    message,
    duration: 1000,
  });
};
//重置表单
const resetForm = () => {
  errorMessage.value = '';
  form.account = '';
  form.password = '';
  formRef.value?.resetFields();
}
// 账号密码登录
const handleLogin = () => {
  formRef.value?.validate(async (valid) => {

    // 使用正则判断账号类型（管理员/普通用户），包含admin前缀的账号视为管理员
    const isAdminAccount = /^admin[\w-]*$/i.test(form.account);
    if (valid) {
      try {
        // 统一提取登录参数
        const loginParams = {
          account: form.account,
          password: form.password,
          last_login_ip: LAST_LOGIN_IP.value,
        };

        // 根据账号类型调用不同store的登录方法
        if (isAdminAccount) {
          await adminStore.login(loginParams);
        } else {
          await userStore.login(loginParams);
        }
        resetForm();
        showMessage('success', '登录成功')
      } catch (error) {
        // 根据账号类型获取对应的错误信息
        errorMessage.value = isAdminAccount ? adminStore.errorMessage : userStore.errorMessage|| '登录失败';
        showMessage('error', '登录失败')
      }
    } else {
      showMessage("warning", "请确保所有字段都填写完整！");
    }
  });
}
// 自动获取地理位置
const getGeoLocation = async () => {
  try {
    const locationData = await getLocation();
    LAST_LOGIN_IP.value = locationData.city; // 只存储城市信息
  } catch (error) {
    LAST_LOGIN_IP.value = ""; // 如果获取地理位置失败，清空或设置默认值
    ElMessage.error('获取地理位置失败，请稍后再试');
  }
};
onMounted(() => {
  getGeoLocation(); // 页面加载时自动获取地理位置
  if (timer.value) {
    clearInterval(timer.value);
    timer.value = null;
  }
});

// 手机号登录表单
const phoneForm = reactive({
  phone: '',
  code: '',
});
const sendingCode = ref(false);
const countdown = ref(0);
const timer = ref(null);
const phoneFormRef = ref(null);
// 发送验证码
const handleSendCode = async () => {
  // 触发表单验证
  if (!phoneFormRef.value) return;
  const valid = await phoneFormRef.value.validateField('phone');
  if (!valid) return;

  if (sendingCode.value) return;
  sendingCode.value = true;

  try {
    const code = await userStore.sendCodeByPhone(phoneForm.phone);
    // 使用现代剪贴板API
    if ('clipboard' in navigator) {
      await navigator.clipboard.writeText(code);
    }

    // 启动倒计时
    countdown.value = 60;
    timer.value = setInterval(() => {
      countdown.value--;
      if (countdown.value <= 0) {
        clearInterval(timer.value);
        timer.value = null;
      }
    }, 1000);

    // 尝试自动填充验证码（如果表单中有验证码输入框）
    setTimeout(() => {
      phoneForm.code = code;
      phoneFormRef.value?.scrollToField('code');
    }, 300);

    ElMessage.success(`您的验证码是：${code}`);

  } catch (error) {
    ElMessage.error('验证码发送失败，请稍后再试');
  } finally {
    sendingCode.value = false;
  }
};
// 手机号登录
const handlePhoneLogin = async () => {
  try {
    await userStore.phoneLogin(phoneForm.phone, phoneForm.code, LAST_LOGIN_IP.value);
    showMessage('success', '登录成功')
    errorMessage.value = '';
    phoneForm.phone = '';
    phoneForm.code = '';
  } catch (error) {
    errorMessage.value = userStore.errorMessage || '登录失败';
    showMessage('error', '登录失败')
  }
};
</script>
<template>
  <div class="login-container">
    <h1>登录</h1>
    <!-- 切换登录方式 -->
    <div class="login-toggle">
      <div @click="switchLoginType('password')" :class="['toggle-item', { active: loginType === 'password' }]">
        账户密码登录
      </div>
      <div @click="switchLoginType('phone')" :class="['toggle-item', { active: loginType === 'phone' }]">
        手机号登录
      </div>
      <div class="slider-bar" :style="{width: '50%',left: loginType === 'password' ? '1%' : '49%'}"/>
    </div>
    <!-- 错误提示 -->
    <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
    <!-- 账户密码登录 -->
    <div v-if="loginType === 'password'" class="account-password-login">
      <el-form ref="formRef" :model="form"
               :rules="rules"
               scroll-to-error
               size="large"
               hide-required-asterisk>
        <el-form-item prop="account">
          <el-input v-model="form.account" placeholder="请输入账号"/>
        </el-form-item>
        <el-form-item prop="password">
          <el-input v-model="form.password" placeholder="请输入密码" show-password type="password"/>
        </el-form-item>
      </el-form>
      <el-button type="success" @click="handleLogin" size="large" class="login-btn">登录</el-button>
    </div>
    <!-- 手机号登录 -->
    <div v-else class="phone-login">
      <el-form ref="phoneFormRef" :model="phoneForm" :rules="rules" scroll-to-error size="large" hide-required-asterisk>
        <el-form-item prop="phone">
          <div class="phone-input">
            <el-input v-model="phoneForm.phone" placeholder="请输入手机号"/>
            <el-button
                type="primary"
                :disabled="sendingCode || countdown > 0"
                @click="handleSendCode"
                class="send-code-btn"
            >
              {{ countdown > 0 ? `${countdown}秒后重发` : '发送验证码' }}
            </el-button>
          </div>
        </el-form-item>
        <el-form-item prop="code">
          <el-input v-model="phoneForm.code" placeholder="请输入验证码"/>
        </el-form-item>
      </el-form>
      <el-button type="success" @click="handlePhoneLogin" size="large" class="login-btn">登录</el-button>
    </div>
  </div>
</template>
<style scoped>
.send-code-btn {
  margin-left: 15px;
  padding: 0 10px;
}

.phone-login {
  width: 80%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.phone-input {
  width: 100%;
  display: flex;
  align-items: center;
  flex-direction: row;
}


.login-container {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.error-message {
  color: red;
}

.account-password-login {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.login-btn {
  font-size: 18px;
  padding: 10px 70px;
  margin-top: 10px;
}

.login-toggle {
  display: flex;
  width: 80%;
  margin: 20px auto 50px auto;
  border-radius: 8px;
  background: #f5f7fa;
  padding: 4px;
  position: relative;
}

.toggle-item {
  flex: 1;
  padding: 12px 0;
  text-align: center;
  cursor: pointer;
  color: #909399;
  transition: all 0.3s ease;
  position: relative;
  z-index: 1;
}

.toggle-item.active {
  color: #409eff;
  font-weight: bold;
}

.toggle-item:hover {
  color: orange;
}

/* 滑动条效果 */
.slider-bar {
  position: absolute;
  height: calc(100% - 8px);
  background: white;
  border-radius: 6px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  z-index: 0;
}
</style>